(function()
{
	var App =
	{
		Models: {},
		Collections: {},
		Views: {},
		Helpers: {}
	};

	App.Helpers.template = function( id )
	{
		return _.template($('#' + id).html());
	};

	App.Models.Task = Backbone.Model.extend(
	{
		validate: function( attributes )
		{
			if( !attributes.title )
			{
				return 'Task title MUSTNOT empty!';
			}
		},

		initialize: function()
		{
			this.on('invalid', function( model, error )
			{
				alert(error);
			});
		}
	});

	App.Views.Task = Backbone.View.extend(
	{
		tagName: 'li',

		render: function()
		{
			this.$el.html(App.Helpers.template('taskTemplate')(this.model.toJSON()));
			return this;
		},

		events:
		{
			'click .edit': 'onEdit',
			'click .delete': 'onDelete'
		},

		onEdit: function()
		{
			var newTaskTitle = prompt('Please input a new Place', this.model.get('title'));
			newTaskTitle && $.trim(newTaskTitle) && this.model.set('title', newTaskTitle);
			this.render();
		},

		onDelete: function()
		{
			this.model.destroy();
			this.$el.remove();
		}
	});

	App.Collections.Task = Backbone.Collection.extend(
	{
		model: App.Models.Task
	});

	App.Views.Tasks = Backbone.View.extend(
	{
		tagName: 'ul',

		initialize: function()
		{
			this.collection.on('add', function( task )
			{
				this.addOne(task);
			}, this);
		},

		render: function()
		{
			this.collection.each(this.addOne, this);
			return this;
		},

		addOne: function( task )
		{
			var taskView = new App.Views.Task(
			{
				model: task
			});

			this.$el.append(taskView.render().el);
		}
	});

	App.Views.addTask = Backbone.View.extend(
	{
		el: '#taskForm',

		events:
		{
			'submit': 'submit'
		},

		submit: function( e )
		{
			e.preventDefault();
			var newTaskTitle = $(this.el).find('input[type=text]').val();
			var newTask = new App.Models.Task(
			{
				title: newTaskTitle,
				level: Math.ceil(10 * Math.random())
			});
			this.collection.add(newTask);
		}
	});

	var taskCollection = new App.Collections.Task(
	[
	    {
		    title: 'go to mall',
		    level: 2
	    },
	    {
		    title: 'go to taobao',
		    level: 4
	    },
	    {
		    title: 'go to baidu',
		    level: 3
	    }
	]);

	var addTaskView = new App.Views.addTask(
	{
		collection: taskCollection
	});

	var tasksView = new App.Views.Tasks(
	{
		collection: taskCollection
	});

	$('#taskList').html(tasksView.render().el);

})();